import Cookies from 'js-cookie'
import Vue from 'vue'
import store from '@/store'

/**
 * 权限
 * @param {*} key
 */
export function hasPermission(key) {
  return true
  return window.SITE_CONFIG['permissions'].indexOf(key) !== -1 || false
}

/**
 * 获取字典数据列表
 * @param dictType  字典类型
 */
export function getDictDataList(dictType) {
  const type = window.SITE_CONFIG['dictList'].find((element) => (element.dictType === dictType))
  if (type) {
    return type.dataList
  } else {
    return []
  }
}

/**
 * 获取字典名称
 * @param dictType  字典类型
 * @param dictValue  字典值
 */
export function getDictLabel(dictType, dictValue) {
  const type = window.SITE_CONFIG['dictList'].find((element) => (element.dictType === dictType))
  if (type) {
    // + ''
    const val = type.dataList.find((element) => (element.dictValue === dictValue))
    if (val) {
      return val.dictLabel
    } else {
      return dictValue
    }
  } else {
    return dictValue
  }
}

/**
 * 清除登录信息
 */
export function clearLoginInfo() {
  store.commit('resetStore')
  // Cookies.remove('token')
  Cookies.remove('MES_ADMIN_KEY')
  localStorage.removeItem('mef_user_id')
  window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = false
}

/**
 * 获取uuid
 */
export function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * 获取svg图标(id)列表
 */
export function getIconList() {
  var res = []
  var list = document.querySelectorAll('svg symbol')
  for (var i = 0; i < list.length; i++) {
    res.push(list[i].id)
  }

  return res
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate(data, id = 'id', pid = 'pid') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (!temp[data[k][pid]] || data[k][id] === data[k][pid]) {
      res.push(data[k])
      continue
    }
    if (!temp[data[k][pid]]['children']) {
      temp[data[k][pid]]['children'] = []
    }
    temp[data[k][pid]]['children'].push(data[k])
    data[k]['_level'] = (temp[data[k][pid]]._level || 0) + 1
  }
  return res
}

export const getToken = (tokenName = 'MES_ADMIN_KEY') => {
  return Cookies.get(tokenName);
};

export const getUserId = () => {
  return localStorage.getItem('mef_user_id')
};

export const transDictObjList = (obj) => {
  let arr = []
  for (let key in obj) {
    let temp = {}
    temp.dictType = key
    let val = []
    if (obj[key].length > 0) {
      obj[key].forEach((item) => {
        val.push({
          dictLabel: item.label,
          dictValue: String(item.value),
        })
      })
    }
    temp.dataList = val
    arr.push(temp)
  }
  return arr
}

// json 对象转 FormData 对象
export const jsonObjToFormObj = (jsonObj) => {
  const formData = new FormData();
  Object.keys(jsonObj).forEach((key) => {
    if (jsonObj[key] instanceof Array) {
      jsonObj[key].forEach((item) => {
        formData.append(key, item);
      });
      return;
    }
    formData.append(key, jsonObj[key]);
  });
  return formData;
};

// get请求对象拼装字符串

export const serializeParam = (obj) => {
  const str = [];
  for (const key in obj) {
    // eslint-disable-next-line no-prototype-builtins
    if (obj.hasOwnProperty(key)) {
      if (!Array.isArray(obj[key])) {
        obj[key] !== undefined ? str.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`) : '';
        // str.push(key + '=' + obj[key]);
      } else {
        const arrStr = obj[key].join(',');
        obj[key] = arrStr;
        str.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`);
      }
    }
  }
  return str.join('&');
};


export const tranSelectArr = (arr, label, value, other) => {
  if (!arr || arr?.length < 1) return [];
  const temp = [];
  arr.forEach((item) => {
    temp.push({
      label: item[label],
      value: item[value],
      [other]: other ? item[other] : '',
    });
  });
  return temp;
};

export const getTreeItem = (treeList, id, key) => {
  for (let i = 0; i < treeList.length; i++) {
    let treeItem = treeList[i]
    if (treeItem[key] === id) {
      return treeItem
    } else {
      if (treeItem.children && treeItem.children.length > 0) {
        let res = getTreeItem(treeItem.children, id, key)
        if (res) {
          return res
        }
      }
    }
  }
}

export const formatDayTime = (dataString) => {
  var time = new Date(dataString);
  var year = time.getFullYear();
  var month = time.getMonth() + 1;
  var day = time.getDate();
  return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)
}

export const transCascader = (key, arrData) => {
  let arr = []
  let returnArr = [] // 存放结果的数组
  let depth = 0 // 定义全局层级
  // 定义递归函数
  function childrenEach(childrenData, depthN) {
    for (var j = 0; j < childrenData.length; j++) {
      depth = depthN // 将执行的层级赋值 到 全局层级
      arr[depthN] = childrenData[j].value
      if (childrenData[j].value == key) {
        returnArr = arr.slice(0, depthN + 1) //将目前匹配的数组，截断并保存到结果数组，
        break
      } else {
        if (childrenData[j].children) {
          depth++
          childrenEach(childrenData[j].children, depth)
        }
      }
    }
    return returnArr
  }
  return childrenEach(arrData, depth)
}